package com.contexticon.logic;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;

import PanelTests.Transcriber5;

import com.contexticon.mediaTest.PlayerTest;

public class TableVerifier implements FocusListener{

	JTable table;
	public JTable getTable() {
		return table;
	}

	PlayerTest player;
	
	// pointer to the last selected row
	int lastSelectedRow = -1;
	JTextArea jtext;
	
	public TableVerifier(JTable t, PlayerTest player) {
		this.player = player;
		this.table = t;
	}
	
	@Override
	public void focusGained(FocusEvent e) {

		// keeps track of last selected row
		lastSelectedRow = table.getSelectedRow();
		//System.out.println("Focus gained at row "+ lastSelectedRow);
		
		//System.out.println("Model contents: " + table.getValueAt(lastSelectedRow, 2));
	}

	@Override
	public void focusLost(FocusEvent e) {
		// TODO Auto-generated method stub
		System.out.println("Focus lost: ");
		
		table.setRowHeight(table.getRowHeight());	
		
		DefaultTableModel ourModel = (DefaultTableModel) table.getModel();
		// check the last row
		int noRows = ourModel.getRowCount();
		Object lastTime = ourModel.getValueAt(noRows-1, 1);
		
		
		// checks whether the focus was lost from the table
		// or from a text area
		String utteranceContent = null;
		if (e.getOppositeComponent() instanceof JTable) {
		     // get the content from the last selected row
			if (lastSelectedRow>=0) {
				utteranceContent = (String) ourModel.getValueAt(lastSelectedRow, 2);
				 System.out.println("lastSelectedRow: " + lastSelectedRow);
				System.out.println("Model: " + utteranceContent);
			}	
		} else if (e.getOppositeComponent() instanceof JTextArea) {	
			// get the content from the text area
			jtext = (JTextArea) e.getSource();
			 utteranceContent = jtext.getText();
			 
			System.out.println("Text area: " + utteranceContent); 
			System.out.println("Model: " + ourModel.getValueAt(lastSelectedRow, 2)); 
		}
		
		
		// if the last row is selected
		// and the end time is not set
		// utteranceContent is not empty
		if ((lastSelectedRow==(noRows-1)) && (lastTime ==null) && (null!=utteranceContent) && (utteranceContent.length()>0)) {
			long currentTime = player.getCurrentTime();
			// set the current time to the last row, as end time
			//ourModel.setValueAt(currentTime, lastSelectedRow, 1);
			// add a new utterance
			//ourModel.addRow(new Object[]{new Float(currentTime), null, null});

		}
		
		
	}
	
	
	
}
